<template>
  <MyDrawer ref="myRef" title="友情链接" :disabled="false" @submit="submit">
    <el-form :model="drawerProps.row" ref="formRef" label-width="120" :rules="rules">
      <el-form-item label="连接名称" prop="title">
        <el-input v-model="drawerProps.row.title"></el-input>
      </el-form-item>
      <el-form-item label="链接地址" prop="link">
        <el-input v-model="drawerProps.row.link"></el-input>
      </el-form-item>
      <el-form-item label="排序值">
        <el-input-number v-model="drawerProps.row.sort" :min="1" :max="10000"></el-input-number>
      </el-form-item>
    </el-form>
  </MyDrawer>
</template>

<script setup lang="ts">
import MyDrawer from "@/components/MyDrawer/index.vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { ref } from "vue";

interface DrawerProps {
  row: any;
  api?: (params: any) => Promise<any>;
  getTable?: () => Promise<any>;
}

const rules: FormRules = {
  title: [
    { required: true, message: "友情链接名称是必须的", trigger: "blur" },
    { message: "链接名称字数在1-20个字之间", max: 20, min: 1 }
  ],
  link: [
    { required: true, message: "链接地址是必须的", trigger: "blur" },
    { message: "链接长度不可超过250个字", max: 250 }
  ]
};

const initData: any = {
  title: "",
  link: "",
  sort: 1
};

const drawerProps = ref<DrawerProps>({ row: JSON.parse(JSON.stringify(initData)) });

const myRef = ref<InstanceType<typeof MyDrawer> | null>();

const acceptParams = (params: any) => {
  drawerProps.value = params;
  myRef.value?.acceptParams();
};

const formRef = ref<FormInstance>();

const submit = () => {
  if (!formRef.value) return;
  formRef.value.validate(async valid => {
    if (!valid) return;
    try {
      await drawerProps.value.api!(drawerProps.value.row);
      ElMessage.success("成功");
      await drawerProps.value.getTable!();
      myRef.value?.close();
    } catch (error) {}
  });
};

defineExpose({ acceptParams });
</script>

<style></style>
